import re

__doc__ = '''
Basic python script to parse the generic .kml file output by

ogr2ogr -f KML output.kml -t_srs EPSG:4326 neighborhoods

where neighborhoods the exploded zip file from the City of Chicago.
The point is to post-process the output to add descriptions, sort
by neighborhood name, and clean up the output styling.
'''

pat1 = re.compile('<Placemark>.*?</Placemark>',re.S)
pat2 = re.compile('<description>(.*)</description>',re.S)
pat3 = re.compile('<i>([^0-9][^<]+)</i>')
pat4 = re.compile('<name>(.*)</name>')
pat5 = re.compile('<Style>.*</Style>')


def replacedesc(match):
    inner = match.groups()[0]
    return '<name>' + pat3.search(inner).groups()[0] + '</name>'


def cleanup(place):
    place = pat2.sub(replacedesc, place)
    place = pat5.sub('<styleUrl>#def</styleUrl>', place)
    return place

kml = open('output.kml', 'r').read()
objs = pat1.findall(kml)
#print objs[0]
objs = [cleanup(x) for x in objs]
#print objs[0]
objs.sort(key = lambda x: pat4.search(x).groups()[0])
#print objs[0]

kml = '''<?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://earth.google.com/kml/2.0">
<Document>
<Style id="def">
  <LineStyle><color>ff0000ff</color><width>3</width></LineStyle>
  <PolyStyle><fill>0</fill></PolyStyle>
  <LabelStyle><color>bbffa0a0</color><colorMode>normal</colorMode><scale>1.4</scale></LabelStyle>
  <Icon>
      <href>root://icons/palette-3.png</href>
      <x>128</x>
      <y>128</y>
      <w>32</w>
      <h>32</h>
</Icon>
</Style>
<Folder>
<name>Chicago neighborhoods</name>
'''
kml += '\n'.join(objs)
kml += '</Folder></Document></kml>'

open('output2.kml', 'w').write(kml)
